<template>
  <div>
    <div
      class="container"
      id="map"
      ref="map"
      style="width: 100vw; height: 100vh"
    />
    <div id="overlay-box" />
    <div id="mouse" />
  </div>
</template>
<script>
// 导入数据
import pharData from '@/assets/data/pharData1.json'
import line1 from '@/assets/data/line1.json'
import line2 from '@/assets/data/line2.json'
// import line3 from '@/assets/data/line3.json'

import 'ol/ol.css'
import TileLayer from 'ol/layer/Tile'
// import Tile from 'ol/layer/Tile'
// import OSM from 'ol/source/OSM'
import { XYZ } from 'ol/source'
import VectorLayer from 'ol/layer/Vector'
import VectorSource from 'ol/source/Vector'

import { Style, Icon, Stroke, Fill } from 'ol/style'
import { Point } from 'ol/geom'
import Overlay from 'ol/Overlay'
import 'ol/ol.css'
import MousePosition from 'ol/control/MousePosition.js'
import { format } from 'ol/coordinate'
import { Map, View, Feature } from 'ol'

import { Polygon } from 'ol/geom'
// import { defaults as defaultControls, OverviewMap } from 'ol/control'

export default {
  data() {
    return {
      map: {},
      pointLayer: {}
    }
  },
  // 在模板渲染成html后调用
  mounted() {
    this.initMap()
    this.clickMap()
    // this.addPoints(coordinate)
  },
  methods: {
    initMap() {
      const mousePositionControl = new MousePosition({
        coordinateFormat: (coordinate) => {
          return format(coordinate, '经度:{x} 纬度:{y}', 4)
        },
        projection: 'EPSG:4326',
        target: 'mouse'
      })
      this.map = new Map({
        target: 'map', // 与div进行绑定，作为地图的容器
        // 添加图层
        layers: [
          // 平铺图层
          new TileLayer({
            // 数据来源
            source: new XYZ({
              // 瓦片数据
              url: 'http://{a-c}.tile.openstreetmap.de/{z}/{x}/{y}.png'
            })
          })
          // new Tile({
          //   source: new OSM() // 图层数据源 OpenStreetMap（简称OSM）开源街道地图
          // })
        ],
        // 视图窗口
        view: new View({
          // 投影坐标系
          projection: 'EPSG:4326',
          center: [113.991251, 30.619935],
          // center: [30.5656419, 114.2623055],
          zoom: 16
        }),
        controls: [mousePositionControl]
      })
    },
    clickMap() {
      // 航标符号数据 101
      console.log(pharData)
      var data = pharData.data

      // this.map.on("click", (e) => {
      //   this.addPoints(e.coordinate);
      // });
      this.addPoints(data)
      this.addLine1()
      this.addLine2()
      this.addLine3()
    },
    /**
     * 根据经纬度坐标添加
     */
    addPoints(data) {
      console.log(data)
      if (Object.keys(this.pointLayer).length === 0) {
        // 矢量图形最大的优点是无论放大、缩小或旋转等不会失真
        // 创建矢量图层
        this.pointLayer = new VectorLayer({
          source: new VectorSource()
        })
        // 图层添加到地图上
        this.map.addLayer(this.pointLayer)
      }

      for (var i = 0; i < data.length; i++) {
        var coordinate = data[i].coordinate
        var pharName = data[i].name
        // 矢量元素
        const feature = new Feature({
          // 坐标信息
          geometry: new Point(coordinate)
        })
        feature.setStyle(
          new Style({
          // 设置图片
            image: new Icon({
              src: 'https://nmmsl.oss-cn-beijing.aliyuncs.com/img/0111.png',
              // anchor: [0.5, 0.5],
              scale: 1.5
            })
          })
        )
        // 添加矢量元素到地图图层上
        // this.pointLayer.getSource().addFeatures([feature]);
        this.pointLayer.getSource().addFeature(feature)

        // 设置文字信息（坐标和名字）
        this.addText(coordinate, pharName)
      }
    },
    addText(coordinate, pharName) {
      const overlayBox = document.getElementById('overlay-box') // 获取div
      const oSpan = document.createElement('span') // 创建span
      oSpan.contentEditable = false // 设置文字不可编辑
      oSpan.id = coordinate[0] // 创建一个id
      const pText = document.createTextNode(pharName) // 创建span的文本信息
      oSpan.appendChild(pText) // 将文本信息添加到span
      overlayBox.appendChild(oSpan) // 将span添加到div中
      const textInfo = new Overlay({
        position: coordinate, // 设置位置
        element: document.getElementById(coordinate[0]),
        offset: [0, 0] // 设置偏移
      })
      this.map.addOverlay(textInfo)
    },

    /**
     * 设置区域
     */
    addLine1() {
      const features = []
      // let lineData = g.features[0];
      let line1Feature = ''
      line1Feature = new Feature({
        // 获取数据
        geometry: new Polygon(line1.data)
      })
      line1Feature.setStyle(
        new Style({
          fill: new Fill({
            color: '#b0e0e6' // 填充颜色
          }),
          stroke: new Stroke({
            width: 2, // 边界宽度
            color: [255, 0, 0, 1] // 边界颜色
          })
        })
      )
      features.push(line1Feature)
      const routeLayer = new VectorLayer({
        source: new VectorSource({
          features: features
        })
      })
      // 添加图层
      this.map.addLayer(routeLayer)
    },

    /**
     * 设置区域
     */
    addLine2() {
      const features = []
      // let lineData = g.features[0];
      let line1Feature = ''
      line1Feature = new Feature({
        geometry: new Polygon(line2.data)
      })
      line1Feature.setStyle(
        new Style({
          fill: new Fill({
            color: '#b0e0e6' // 填充颜色
          }),
          stroke: new Stroke({
            width: 1, // 边界宽度
            color: [255, 0, 0, 1] // 边界颜色
          })
        })
      )
      features.push(line1Feature)
      const routeLayer = new VectorLayer({
        source: new VectorSource({
          features: features
        })
      })
      // 添加图层
      this.map.addLayer(routeLayer)
    }
  }
}
</script>
<style scoped>
.container {
  width: 100%;
  height: 100%;
  /* margin: 50px auto; */
  margin: 0 auto;
  border: 1px solid #42b983;
}
#mouse {
 position: absolute;
  bottom: 10px;
  left: 10px;
  z-index: 10;
  width: 210px;
  height: 32px;
  color: #f00;
  /* background: #fff; */
  vertical-align: baseline;
}
#overlay-box{
  width: 1px;
  height: 1px;
}
</style>
